<?php

namespace Kollway\CodeGenerator\Generators;

class ControllerGenerator extends Generator
{
    public function generateControllerString()
    {
        $list_method_string = $this->getListMethodString();
        $get_form_method_string = $this->getGetFormMethodString();
        $post_form_method_string = $this->getPostFormMethodString();

        $controller = <<<CONTROLLER
<?php

namespace App\Http\Controllers\Admin;

use App\Model\\$this->model_name;

class {$this->model_name}Controller extends KollwayAdminController
{
$list_method_string\n
$get_form_method_string\n
$post_form_method_string
}
CONTROLLER;

        $this->content = $controller;

        return $controller;
    }

    /**
     * 获取列表方法字符串
     * @return string
     */
    protected function getListMethodString()
    {
        $list_method = <<<CONTROLLER
    public function getList()
    {
        \$this->markPage();\n
CONTROLLER;

        // 模糊搜索
        if ($this->search_fields) {
            $fields = json_encode($this->search_fields);
            $list_method .= <<<CONTROLLER
        \$keyword = trim(request('keyword'));\n\n
        \$builder = $this->model_name::recent()->like($fields, \$keyword);\n\n
CONTROLLER;
        } else {
            $list_method .= <<<CONTROLLER
        \$builder = $this->model_name::recent();\n\n
CONTROLLER;
        }

        $list_method .= <<<CONTROLLER
        \$list = \$this->pageSelect(\$builder);\n
CONTROLLER;
        if ($this->search_fields) {
            $list_method .= <<<CONTROLLER
        return view('$this->table.list', compact('list', 'keyword'));
    }
CONTROLLER;
        } else {
            $list_method .= <<<CONTROLLER
        return view('$this->table.list', compact('list'));
    }
CONTROLLER;
        }


        return $list_method;
    }

    /**
     * 获取表单编辑方法字符串
     * @return string
     */
    protected function getGetFormMethodString()
    {
        $form_string = <<<FORM
    public function getForm()
    {
        \$id = request('id');
        \$data = $this->model_name::find(\$id);
        
        return view('$this->table.form', compact('id', 'data'));
    }
FORM;

        return $form_string;
    }

    /**
     * 获取保存表单方法字符串
     * @return string
     */
    protected function getPostFormMethodString()
    {
        $post_form_string = <<<FORM
    public function postForm($this->model_name \$$this->table)
    {
        \$data = request()->all();
        
        if (\$err = \${$this->table}->validate(\$data)) {
            return \$this->ajaxFail(\$err);
        }
        
        \$success = \${$this->table}->addOrSave(\$data);
        
        \$type = \$data['id'] <= 0 ? '新增' : '保存';
        if (\$success) {
            return \$this->ajaxSuccess(\$type . '成功', \$this->getMarkedPage());
        } else {
            return \$this->ajaxFail(\$type . '失败');
        }
    }
FORM;
        return $post_form_string;
    }
}